package class04;

import utils.ListNode;

/**
 * @ClassName Code06_有序链表合并
 * @Description: 有序链表合并
 * @Author: WangWenpeng
 */
public class Code06_有序链表合并 {
    public static ListNode mergeTwoLists(ListNode h1, ListNode h2) {
        //清除链表为空的情况
        if (h1 == null || h2 == null) {
            return h1 == null ? h2 : h1;
        }
        //找到两个链表中较小的作为新的头
        ListNode head = h1.value <= h2.value ? h1 : h2;
        ListNode cur1 = head.next;
        ListNode cur2 = head == h1 ? h2 : h1;
        ListNode pre = head;

        while (cur1 != null && cur2 != null) {
            if (cur1.value <= cur2.value) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        //
        pre.next = cur1 != null ? cur1 : cur2;
        return head;
    }
}
